<template>
  <el-card shadow="hover">
    <template #header>
      <el-button
        type="primary"
        :icon="Plus"
        @click="trademarkShow({ tmName: '', logoUrl: '' })">
        添加
      </el-button>
    </template>

    <el-table :data="list" v-loading="loading" border>
      <el-table-column label="序号" type="index" width="80" align="center" />
      <el-table-column label="品牌名称" prop="tmName" />
      <el-table-column label="品牌LOGO">
        <template v-slot="{ row, $index }">
          <!-- row: 当前行数据对象 -->
          <el-image
            :src="row.logoUrl"
            style="width: 100px; height: 60px"></el-image>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template v-slot="{ row, $index }">
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="trademarkShow(row)"></el-button>
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除"
            placement="top">
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="removeTrademark(row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="isShow" :title="trademaskForm.id ? '修改' : '添加'">
      <el-form
        :model="trademaskForm"
        label-width="140px"
        :rules="rules"
        ref="formRef">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            v-model="trademaskForm.tmName"
            autocomplete="off"
            placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- action: 处理图片上传请求的url
                  不能直接写目标地址  => 跨域了
                  必须写一个带代理前缀路径的路径
            show-file-list: false  单个图片 -->
          <el-upload
            class="avatar-uploader"
            :action="`${VITE_BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img
              v-if="trademaskForm.logoUrl"
              :src="trademaskForm.logoUrl"
              class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isShow = false">返回</el-button>
          <el-button type="primary" @click="confirm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-pagination
      style="margin-top: 20px"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[3, 6, 9]"
      layout="prev, pager, next, jumper, ->, sizes, total"
      @current-change="getList"
      @size-change="getList" />
  </el-card>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import type {
  trademarkModel,
  trademarksModel,
} from "@/api/product/model/trademarkModel";
import {
  removetrademarkApi,
  savetrademarkApi,
  trademarkpageListApi,
  updatetrademarkApi,
} from "@/api/product/trademark";
import { Delete, Edit, Plus } from "@element-plus/icons-vue";

import {
  ElMessage,
  type UploadProps,
  type FormInstance,
  ElMessageBox,
} from "element-plus";

import { ref, onMounted, reactive, nextTick } from "vue";
/* 分页列表 start */
const list = ref<trademarksModel>([]); // 当前页的列表
const currentPage = ref(1); // 当前页码
const pageSize = ref(3); // 每页数量
const total = ref(0); // 总数量

const loading = ref(false); //加载

// 获取请求分页列表数据
const getList = async () => {
  loading.value = true;
  const result = await trademarkpageListApi(currentPage.value, pageSize.value);
  total.value = result.total;
  list.value = result.records;
  loading.value = false;
};

// 初始化请求
onMounted(() => {
  getList();
});

/* 分页列表 end */

/* 添加与修改 start */
const VITE_BASE_URL = import.meta.env.VITE_BASE_URL;

const isShow = ref(false); //显示添加或者修改

// 表单的内容
const trademaskForm = ref<trademarkModel>({
  tmName: "",
  logoUrl: "",
});

// 添加与修改
const trademarkShow = (trademask: trademarkModel) => {
  isShow.value = true;
  trademaskForm.value.id = trademask.id;
  trademaskForm.value.tmName = trademask.tmName;
  trademaskForm.value.logoUrl = trademask.logoUrl;

  //  手动清除校验错误信息:
  // 内部的校验操作是异步执行, 我们清除操作发生校验之前
  // formRef.value?.clearValidate()

  // 必须延迟执行校验操作, 让它在自动校验之后清除

  // 使用定时器(宏任务)  可以的
  // setTimeout(() => {
  //   formRef.value?.clearValidate([]);
  // }, 0);

  // 使用nextTick(微任务)  有问题
  // 原因: 校验的异步任务在当前nextTick微任务之后才执行
  // nextTick(() => {
  //   formRef.value?.clearValidate()
  // })

  // 使用2个嵌套的nextTick  可以
  nextTick(() => {
    nextTick(() => {
      formRef.value?.clearValidate([]);
    });
  });
};

// 上传图片
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // trademarkForm.logoUrl = URL.createObjectURL(uploadFile.raw!)  // 产生的url是一个临时的, 后面不能再用
  trademaskForm.value.logoUrl = response.data;
  // 清除logo的错误提示信息
  formRef.value?.clearValidate(["logoUrl"]);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type !== "image/jpg" &&
    rawFile.type !== "image/png" &&
    rawFile.type !== "image/gif"
  ) {
    ElMessage.error("请上传jpg或者png格式的图片");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("上传图片的大小不能超过50kB!");
    return false;
  }
  return true;
};

const formRef = ref<FormInstance>();
// 表单校验规则列表
const rules = reactive({
  tmName: [
    { required: true, message: "品牌名称是必须的", trigger: "blur" }, // 必须的
    // 使用内置校验规则实现
    // {min: 3, max: 6, message: '品牌名称长必须在3到6位'/* , trigger: 'change' */}, // 长度必须是3到6位
    // 使用自定义校验来实现
    { validator: validateTmName, trigger: "change" },
  ],
  logoUrl: [{ required: true, message: "品牌LOGO是必须的" }],
});

function validateTmName(rule: any, value: any, callback: any) {
  if (value.length < 3 || value.length > 6) {
    // 如果校验不通过, 调用callback指定包含错误信息的error, 或者直接指定错误信息
    // callback(new Error('品牌名称长必须在3到6位'))
    callback("品牌名称长必须在3到6位!!!!");
  } else {
    // 校验通过时, 直接调用callback, 不传递任何参数
    callback();
  }
}
// 确定提交
const confirm = async () => {
  // 对表单进行统一校验
  formRef.value?.validate(async (valid) => {
    if (valid) {
      // valid校验是否通过
      if (trademaskForm.value.id) {
        await updatetrademarkApi(trademaskForm.value);
      } else {
        await savetrademarkApi(
          trademaskForm.value.tmName,
          trademaskForm.value.logoUrl
        );
      }
      // 成功之后, 隐藏dialog, 重新获取列表显示, 提示添加或更新成功
      ElMessage.success(`${trademaskForm.value.id ? "修改" : "添加"}成功`);
      isShow.value = false;
      getList();
    }
  });
};

/* 添加与修改 end */

/* 删除数据 */

const removeTrademark = async (row: trademarkModel) => {
  // console.log(id);

  ElMessageBox.confirm(`确认删除${row.tmName}吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "返回",
    type: "success",
  })
    .then(async () => {
      // 发请求
      await removetrademarkApi(row.id as number);

      ElMessage({
        type: "success",
        message: "删除成功",
      });

      // 如果当前页就一条数据，请求显示上一页
      if (list.value.length === 1) {
        // 将当前页码减1
        currentPage.value -= 1;
      }
      getList();
    })
    .catch((error) => {
      if (error === "cancel") {
        ElMessage({
          type: "info",
          message: "取消删除",
        });
      }
    });
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.tooltip-base-box {
  width: 600px;
}
.tooltip-base-box .row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tooltip-base-box .center {
  justify-content: center;
}
.tooltip-base-box .box-item {
  width: 110px;
  margin-top: 10px;
}
</style>
